package com.netease.pluginproject;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.lang.reflect.Method;

import dalvik.system.DexClassLoader;

/**
 * 创建日期：2021/9/30 10:59
 *
 * @author tony.sun
 * 类说明：
 */

public class PluginManager {
    private static final String TAG = "PluginManager";
   private static volatile  PluginManager instance;
    private Context context;
    private DexClassLoader dexClassLoader;
    private Resources resources;

    private PluginManager(Context context) {
       this.context=context;
   }
   
   public static PluginManager getInstance(Context context) {
    if (instance == null) {
        synchronized (PluginManager.class) {
            if (instance == null) {
                instance = new PluginManager(context);
            }
        }
    }
    return instance;
   }

    /**加载插件
     * 1.加载类，
     * 2.加载布局
     */
   public void loadPlugin(){
       //获取apk的路径 /storage/emulated/0/p.apk
       File file = new File(Environment.getExternalStorageDirectory() + File.separator + "p.apk");
       //判断文件是否为空
       if (!file.exists()) {
           Log.d(TAG, "loadPlugin: 插件不存在");
           return;
       }
       String pluginPaht = file.getAbsolutePath();// /storage/emulated/0/p.apk
       Log.d(TAG, "loadPlugin: "+pluginPaht);// /storage/emulated/0/p.apk
       //加载类
       loadClass(pluginPaht);
       //加载布局
       loadLayout(pluginPaht);
   }

    /**
     * 根据apk的路径来进行加载类
     * @param pluginPaht apk的路径 /storage/emulated/0/p.apk
     */
    private void loadClass(String pluginPaht) {
        /**
         * dexClassLoader需要一个缓存目录
         * /data/data/当前应用的包名/pDir
         */
        File fileDir = context.getDir("pDir", Context.MODE_PRIVATE);
        dexClassLoader = new DexClassLoader(pluginPaht,  fileDir.getAbsolutePath(), null, context.getClassLoader());
    }
    /**
     * 根据apk的路径来进行加载布局资源
     * @param pluginPaht apk的路径 /storage/emulated/0/p.apk
     */
    private void loadLayout(String pluginPaht) {
        try {
            //加载资源
            AssetManager assetManager = AssetManager.class.newInstance();
            Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);//他是类类型Class
            addAssetPath.invoke(assetManager,pluginPaht);//插件包路径

            //宿主的资源配置
            Resources r = context.getResources();
            //特殊的resources 加载插件里面的资源 Resources
            //参数2,3 资源配置信息
            resources = new Resources(assetManager, r.getDisplayMetrics(), r.getConfiguration());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 下面两个时为外面提供方法，可以获取类，获取资源
     * @return
     */
    public DexClassLoader getDexClassLoader() {
        return dexClassLoader;
    }
    public Resources getResources() {
        return resources;
    }
}
